<template>
  <el-container>
    <el-header>
      <div class="header-content">
        <img src="../public/basicprofile.jpg" alt="省料侠Logo" class="logo">
        <div class="nav-links">
          <NuxtLink to="https://www.shengliaoxia.top/admin">门窗设计</NuxtLink>
          <NuxtLink to="https://www.shengliaoxia.top/admin/optimization/record">历史记录</NuxtLink>
          <NuxtLink v-if="userData" to="https://www.shengliaoxia.top/admin/user/profile">{{userData.userName}}</NuxtLink>
          <NuxtLink v-if="!userData" to="https://www.shengliaoxia.top/admin/login?redirect=%2Findex">登录</NuxtLink>
          <NuxtLink v-if="!userData" to="https://www.shengliaoxia.top/admin/register">注册</NuxtLink>
          <el-dropdown>
            <span class="el-dropdown-link">
              相关文章
              <el-icon class="el-icon--right"><arrow-down /></el-icon>
            </span>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item class="dropdown-item">
                  <a href="https://blog.csdn.net/we_we_qiong/article/details/146603666" target="_blank" class="dropdown-link">网站起源</a>
                </el-dropdown-item>
                <el-dropdown-item class="dropdown-item">
                  <a href="https://blog.csdn.net/we_we_qiong/article/details/146396393" target="_blank" class="dropdown-link">持续更新</a>
                </el-dropdown-item>
                <el-dropdown-item class="dropdown-item">
                  <NuxtLink to="/about">关于我们</NuxtLink>
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
        <!-- <div class="auth-buttons">
          <el-button type="text" class="login-btn" @click="showLoginDialog">登录</el-button>
          <el-button type="primary" class="register-btn" @click="showRegisterDialog">注册</el-button>
        </div> -->
      </div>
    </el-header>
    <el-main>
      <el-container>
        <el-main>
          <div class="operation-area">
            <div class="input-area">
              <el-card class="input-card">
                <div slot="header" class="clearfix">
                  <h3 class="clearfix">原材料输入</h3>
                </div>
                <el-input 
                  class="el-input-text" 
                  v-model="materialsInput" 
                  :placeholder="materialsPlaceholder" 
                  type="textarea"
                />
              </el-card>
              <el-card class="input-card">

                <div slot="header" class="clearfix">
                  <h3 class="clearfix">需求输入</h3>
                </div>
                <el-input 
                  class="el-input-text" 
                  v-model="partsInput" 
                  :placeholder="partsPlaceholder" 
                  type="textarea" 
                />
              </el-card>
              <el-card class="qrcode">
                <h3>微信小程序扫描下面二维码</h3>
                <img src="../public/download.jpg" alt="" srcset="" style="width: 200px;">
              </el-card>
            </div>
            <div class="button-area">
              <el-button type="primary" size="large" @click="calculate">开始优化</el-button>
              <el-button type="primary" size="large" @click="generateFile">导出优化</el-button>
            </div>
            <div class="result-area">
              <el-card>
                <h3>优化结果</h3>


                <div class="summary"  v-if="result">
                  <div class="summary-header">方案汇总信息：</div>
                  <div class="summary-brief">
                    <span>原材料总数：{{ result.material.map(t=>t.count).reduce((a,b)=>a+b) }}</span>
                    <span>总体利用率：{{ (result.fitness*100).toFixed(2)}}%</span>
                    <span>损耗统计：{{ result.loss }}</span>
                  </div>
                   <div class="table-section">
                    <div class="table-header">原料规格：
                      <span class="table-cell" v-for="(length, index) in result.materialLengthToCount">{{ index }}x{{ length }} <span></span></span>
                    </div>
                  </div>
                  <div class="table-section">
                    <div class="table-header">下料规格：
                      <span class="table-cell" v-for="(length, index) in result.partLengthToCount">{{ index }}x{{ length }} <span></span></span>
                    </div>
                  </div>
                  <div v-for="(plan, index) in result.material" :key="index" class="plan-item">
                    <div class="plan-content">
                      <span class="plan-text">{{index + 1}}、
                        <span v-for="(segment, sIndex) in plan.parts" :key="sIndex">
                          {{segment.mark}}){{segment.length}}x{{segment.count}}
                          <span v-if="sIndex < plan.parts.length - 1">&nbsp;&nbsp;</span>
                        </span>
                      </span>
                      <span class="plan-text">
                        <span
                          class="material-info">需要{{plan.length}}材料 {{plan.count}}根 余{{plan.remaining}}</span>
                      </span>
                    </div> 
                  </div> 
                </div>
                <el-text v-else style="display: block; width: 100%; color: #999;">请添加原材料和待切割零件后点击计算</el-text>
              </el-card>
            </div>
          </div>
        </el-main>
        <!-- <el-aside width="360px">
          <div class="history-area">
            <el-card>
              <h3>历史记录</h3>
              <template v-if="!userData">
                <el-text style="display: block; width: 100%; color: #999;">未登录</el-text>
              </template>
              <template v-else-if="historyData.length<1">
                <el-text style="display: block; width: 100%; color: #999;">暂无历史记录</el-text>
              </template>
              <template v-else>
                <el-table :data="historyData" style="width: 100%">
                  <el-table-column prop="time" label="优化时间" />
                  <el-table-column prop="rate" label="优化率" />
                </el-table>
              </template>
            </el-card>
            <el-card style="text-align: center;margin-top: 20px;">
              <h3>微信小程序扫描下面二维码</h3>
              <img src="../public/download.jpg" alt="" srcset="" style="width: 200px;">
            </el-card>
          </div>
        </el-aside> -->
      </el-container>
    </el-main>

    <!-- 添加备案信息 -->
    <el-footer style="text-align: center; padding: 20px; background-color: #f5f7fa;">
      <div>
        <a href="https://beian.miit.gov.cn/" target="_blank" style="color: #666; text-decoration: none;">
          冀ICP备2025108558号
        </a>
      </div>
    </el-footer>

    <el-dialog v-model="loginDialogVisible" title="登录" width="30%">
      <el-form :model="loginForm" label-width="80px">
        <el-form-item label="手机号">
          <el-input v-model="loginForm.phone" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item label="密码">
          <el-input v-model="loginForm.password" type="password" placeholder="请输入密码" />
        </el-form-item>
        <el-form-item label="验证码">
          <el-input v-model="loginForm.captcha" placeholder="请输入验证码" style="width: 60%">
            <template #append>
              <img :src="captchaImage" alt="验证码" style="height: 32px; cursor: pointer" />
            </template>
          </el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="handleCancel">取消</el-button>
        <el-button type="primary" @click="handleLogin">登录</el-button>
      </template>
    </el-dialog>

  </el-container>
</template>

<script setup>
import { NuxtLink } from '#components'
import { ref,onMounted } from 'vue'
import { useHead } from '#imports'
import { ArrowDown } from '@element-plus/icons-vue'
import { useRoute } from 'vue-router'
import { computed } from 'vue'
const userData = ref(null)

const getCookies = (name) =>{
  
  const value = `; ${document.cookie}`
  const parts = value.split(`; ${name}=`)
  if (parts.length === 2) return parts.pop().split(';').shift()
}
onMounted(() => {
  console.log('页面已加载')
  const route = useRoute()
  let header = {};
  let token = getCookies('Admin-Token');
  if(token != null){
    header = {
      'Authorization': token,
    }
     $fetch('https://www.shengliaoxia.top/wx_api/getInfo', {
      method: 'GET',
      headers: header
    }).then(res => { 
      console.log(res);
      if(res.code == 200){
        userData.value = res.user;
      }
    });
  }
  // 获取查询参数
  const queryParams = computed(() => route.query);
  console.log(queryParams.value.id);
  if(queryParams.value.id != null){ 
    $fetch('https://www.shengliaoxia.top/wx_api/optimization/record/'+queryParams.value.id, {
      method: 'GET',
      headers: header
    }).then(res => { 
      console.log(res);
      if(res.code == 200){
        result.value = JSON.parse(res.data.data);
      }
    });
  }
})



const materialsPlaceholder = computed(() => 
  `请输入原材料信息，每行一组数据，格式：长度 数量\n例如：\n2000 5\n3000 3`
)

const partsPlaceholder = computed(() =>
  `请输入待切割零件信息，每行一组数据，格式：编号 长度 数量\n例如：\nA 500 10\nB 800 5`
)
// 添加SEO配置
useHead({
  title: '省料侠 - 专业材料优化计算工具',
  meta: [
    { name: 'description', content: '省料侠,一维下料,下料软件,线材,型材,钢管,卡纸,光伏支架,下料助手,一维下料算法，省料侠提供专业的材料优化计算服务，帮助您最大化材料利用率，减少浪费，节约成本。' },
    { name: 'keywords', content: '省料侠,一维下料,下料软件,下料,线材,电缆,钢管,卡纸,型材,材料优化,切割计算,省料工具,材料利用率,优化算法' },
    { property: 'og:title', content: '省料侠 - 专业材料优化计算工具' },
    { property: 'og:description', content: '智能材料优化计算工具，提高材料利用率，降低生产成本' },
    { property: 'og:image', content: '/basicprofile.jpg' },
    { property: 'og:url', content: 'https://www.shengliaoxia.top' }
  ],
  link: [
    { rel: 'canonical', href: 'https://www.shengliaoxia.top' }
  ]
})

const materialsInput = ref('6400 99\n6000 99\n5400 99\n')
const partsInput = ref('')
const result = ref(null)
const historyData = ref(null)
const loginDialogVisible = ref(false)
const loginForm = ref({
  phone: '',
  password: '',
  captcha: ''
})
const captchaImage = ref('')

historyData.value = []
const generateFile = async () => {
  try {
    if (!result.value) {
      throw new Error('请先进行优化计算')
    }

    const response = await $fetch('/wx_api/optimization/generatePdf', {
      method: 'POST',
      body: result.value,
      responseType: 'blob'
    })

    // 获取文件名
    const filename = '优化结果.pdf'

    // 处理文件流
    const url = window.URL.createObjectURL(new Blob([response]))
    const a = document.createElement('a')
    a.href = url
    a.download = filename
    document.body.appendChild(a)
    a.click()
    document.body.removeChild(a)
    window.URL.revokeObjectURL(url)

  } catch (error) {
    console.error('导出文件出错:', error)
    ElMessage.error(`导出文件失败: ${error.message}`)
  }
}

const calculate = async () => {
  try {
    // 解析原材料数据
    const materials = materialsInput.value.trim().split('\n')
      .filter(line => line.trim())
      .map(line => {
        const [length, count] = line.trim().split(/\s+/)
        return {
          length: parseFloat(length),
          count: parseInt(count)
        }
      })

    // 解析零件数据
    const parts = partsInput.value.trim().split('\n')
      .filter(line => line.trim())
      .map(line => {
        const [mark, length, count] = line.trim().split(/\s+/)
        return {
          mark,
          length: parseFloat(length),
          count: parseInt(count)
        }
      })

    // 构造请求数据
    const requestData = {
      materials,
      parts
    }
    console.error('优化计算入参:', JSON.stringify(requestData));

    let header = {};
    let token = getCookies('Admin-Token');
    if(token != null){
      header = {
        'Authorization': token,
      }
    }
    // 修改API调用方式，使用相对路径：
    const data = await $fetch('/wx_api/optimization/optimize', {
      method: 'POST',
      headers: header,  
      body: requestData
    })
    
    result.value = data
  } catch (error) {
    console.error('优化计算出错:', error)
    result.value = `优化计算失败: ${error.message}`
  }
}


const showLoginDialog = () => {
  // loginDialogVisible.value = true
  // 这里可以添加获取验证码图片的逻辑
  alert('功能尚未实现')
}
const showRegisterDialog = () => {
  alert('功能尚未实现')
}

const handleLogin = () => {
  // 处理登录逻辑
}

const handleCancel = () => {
  loginDialogVisible.value = false
}
</script>


<style scoped>
.el-header {
  background-color: #409EFF;
  color: white;
  line-height: 60px;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 20px;
}

.logo {
  height: 40px;
}

.nav-links {
  display: flex;
  align-items: center;
  gap: 20px;
}

.nav-links a,
.nav-links .nuxt-link-active,
.nav-links .el-dropdown-link {
  color: white;
  text-decoration: none;
  font-size: 14px;
  display: flex;
  align-items: center;
}

.nav-links .el-dropdown-link {
  padding: 0;
  outline: none;
}

.nav-links .el-dropdown-link .el-icon {
  margin-left: 5px;
}

.auth-buttons {
  display: flex;
  align-items: center;
}

.login-btn {
  color: white !important;
}

.register-btn {
  margin-left: 10px !important;
}

.el-container {
  height: 100vh;
  width: 100%;
  margin: 0;
  padding: 0;
}

.el-container .el-container {
  height: calc(100vh - 120px)
}

.el-main {
  height: calc(100vh - 120px);
  width: 100%;
  padding: 0;
  margin: 0;
}

.operation-area {
  display: flex;
  flex-direction: column;
  height: 100%;
}

.input-area {
  margin-top: 20px;
  display: flex;
  flex-direction: row;
}

.input-card {
  flex: 1;
  margin-bottom: 20px;
  margin-left: 10px;
}
.el-input-text .el-textarea__inner{
  width: 100%;
  height: 300px;
}
.qrcode{
  text-align: center;
  margin-left: 20px;
  box-sizing: border-box;
  height: 290px;
}

.button-area {
  margin: 0px 0px 20px 0;
  text-align: center;
}

.result-area {
  flex: 1;
  margin-left: 10px;
}

.history-area {
  height: 100%;
  margin-left: 10px;
}

.clearfix:before,
.clearfix:after {
  display: table;
  content: "";
}

.clearfix:after {
  clear: both
}
h3{
  margin: 0;
  margin-bottom: 10px;
  font-size: 1em;
}


.summary {
		margin-bottom: 48rpx;
		padding: 32rpx;
		background-color: #F6F8FA;
		border-radius: 12px;
	}

	.summary-header {
		font-size: 16px;
		font-weight: bold;
		color: #333333;
		margin-bottom: 20rpx;
	}

	.summary-brief {
		display: flex;
		align-items: center;
		gap: 40rpx;
		margin-bottom: 12rpx;
	}

	.summary-brief text {
		font-size: 14px;
		color: #333333;
	}

	.table-section {
		margin-top: 0rpx;
	}

	.table-header {
		font-size: 14px;
		color: #333333;
		margin-bottom: 16rpx;
	}

	.table-row {
		display: flex;
		padding: 12rpx 0;
	}

	.table-cell {
		width: 80px;
		font-size: 14px;
		color: #333333;
		text-align: center;
	}

	.table-cell:first-child {
		color: #666666;
		text-align: left;
		width: 120rpx;
		flex: none;
	}

	.header-row {
		color: #666666;
	}

	.plans {
		display: flex;
		flex-direction: column;
		gap: 30rpx;
	}

	.plan-item {
		background-color: #F6F8FA;
		border-radius: 12px;
		padding: 0rpx;
		margin-bottom: 8rpx;
	}

	.plan-content {
		display: flex;
		align-items: flex-start;
		justify-content: space-between;
		border-bottom: 1px solid;
	}

	.material-info {
		text-align: right;
	}

	.plan-text {
		font-size: 14px;
		line-height: 1.5;
		color: #333333;
	}

	.no-result {
		display: flex;
		justify-content: center;
		align-items: center;
		height: 400rpx;
		color: #999999;
		font-size: 14px;
	}
	.selectable {
		user-select: text;
	}
  :deep(.el-textarea__inner){
    height: 217px;
  }
@media (max-width: 768px) {
  .input-area {
    flex-direction: column;
  }
  :deep(.el-textarea__inner){
    height: 117px;
  }
  .input-card {
    margin-left: 0;
    width: 100%;
  }
  
  .qrcode {
    margin-left: 0;
    margin-top: 10px;
    height: auto;
  }

  .button-area {
    margin: 10px 0;
  }

  .result-area {
    margin-left: 0;
    width: 100%;
  }
  
  .summary {
    padding: 16px;
  }
    
  .plan-content {
    flex-direction: column;
    gap: 8px;
  }
}

</style>
